const { getList, getDetail, newBlog, updateBlog, delBlog } = require('../controller/blog')
const { successModel, errorModel } = require('../model/resModel')

const loginCheck = req => {
    if (!req.session.username) {
        return Promise.resolve(
            new errorModel('尚未登陆')
        )
    }
}

const handleBlogRouter = (req, res) => {
    const method = req.method
    const id = req.query.id
    if (method === 'GET' && req.path === "/api/blog/list") {
        let author = req.query.author || ''
        const keywords = req.query.keywords || ''
        if (req.query.isadmin) {
            const loginCheckResult = loginCheck(req)
            if (loginCheckResult) {
                return loginCheckResult
            }
            author = req.session.username
        }
        const result = getList(author, keywords)
        return result.then((listData) => {
            return new successModel(listData)
        })
    }

    if (method === 'GET' && req.path === "/api/blog/detail") {
        // const detailData = getDetail(id)
        // return new successModel(detailData)
        const result = getDetail(id)
        return result.then((detailData) => {
            return new successModel(detailData)
        })
    }
    if (method === 'POST' && req.path === "/api/blog/new") {
        // const blogData = req.body
        // const data = newBlog(blogData)
        // return new successModel(data)
        const loginCheckResult = loginCheck(req)
        if (loginCheckResult) {
            return loginCheckResult
        }
        req.body.author = req.session.username
        const result = newBlog(req.body);
        return result.then((data) => {
            return new successModel(data)
        })
    }
    if (method === 'POST' && req.path === "/api/blog/update") {

        const loginCheckResult = loginCheck(req)
        if (loginCheckResult) {
            return loginCheckResult
        }
        const result = updateBlog(id, req.body)
        return result.then((val) => {
            if (val) {
                return new successModel()
            } else {
                return new errorModel('更新博客失败')
            }
        })
    }
    if (method === 'POST' && req.path === "/api/blog/del") {
        const loginCheckResult = loginCheck(req)
        if (loginCheckResult) {
            return loginCheckResult
        }
        const author = 'req.session.username'
        const result = delBlog(id, author)
        return result.then((val) => {
            if (val) {
                return new successModel()
            } else {
                return new errorModel('删除失败')
            }
        })
    }
}
module.exports = handleBlogRouter